<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="login">
      <van-field
        :required="!code"
        v-model="code"
        name="用户名"
        label="手机号"
        placeholder="请填写手机号 "
        :rules="reuse.mobile"
      />
      <van-field
        :required="!text"
        v-model="text"
        type="text"
        name="密码"
        label="验证码"
        placeholder="验证请填写验证码码"
        :rules="reuse.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          :loading="loade"
          :disabled="loade"
          type="info"
          native-type="submit"
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
// import axios from '../../utils/request'
import { Login } from '../../api/user.js'
export default {
  data() {
    return {
      loade: false,
      code: '13866666661',
      text: '246810',

      reuse: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不正确'
          }
        ],
        code: [
          {
            required: true,
            message: '验证吗不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证吗格式不正确'
          }
        ]
      }
    }
  },

  methods: {
    ...mapMutations('user', ['setToken']),
    async login() {
      this.loade = true
      console.log(this.$route.query.back)

      // 不能给提交按钮注册click来发送请求 ==> 因为表单校验不通过的时候，也会触发
      // 正确做法：
      console.log('登录中....')
      try {
        const res = await Login(this.code, this.text)
        console.log(res.data)
        this.loade = true
        this.setToken(res.data)
        // console.log(this.$route.query.back)
        this.$router.push(this.$route.query.back || '/home')
      } catch (e) {
        alert(e)
      }
      this.loade = false
    }
  }
}
</script>

<style></style>
